<?php

namespace App\Http\Resources;

use App\Models\Comment;
use Illuminate\Http\Resources\Json\JsonResource;

class CommentResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'key' => $this->key,
            'tid' => $this->tid,
            'detail_excerpt' => $this->detail_excerpt,
            'floor_num' => $this->floor_num,
            'like_count' => $this->like_count,
            'is_main_floor' => $this->is_main_floor,
            'floor_num_human' => $this->getFloorNumHuman($this->resource),
            'pid' => $this->pid,
            'root_id' => $this->root_id,
            'created_at' => $this->created_at->format('Y-m-d H:i'),
            'topic' => new TopicResource($this->whenLoaded('topic')),
            'user' => new UserResource($this->whenLoaded('user')),
            'parent' => new static($this->whenLoaded('parentComment')),
            'detail' => new CommentDetailResource($this->whenLoaded('detail')),
            'first_comments' => static::collection($this->whenLoaded('firstComments')),
            'is_liked' => $this->when(isset($this->is_liked), $this->is_liked),
            'hide' => new CommentHideResource($this->whenLoaded('hide'))
        ];
    }

    private function getFloorNumHuman(Comment $comment)
    {
        if ($comment->is_main_floor) {
            return '主楼';
        } elseif ($comment->floor_num > 0) {
            return $comment->floor_num . '楼';
        } else {
            return '';
        }
    }
}
